package com.ajavaer.framework.start;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.ajavaer.framework.cache.type.CacheEngine;
import com.ajavaer.framework.config.CacheConfig;
import com.ajavaer.framework.config.CacheEngineConfig;
import com.ajavaer.framework.config.ShiroConfig;
import com.ajavaer.framework.filter.AjaxRequestFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
@ComponentScan(basePackages = {"com.ajavaer.framework.config"})
@ConditionalOnProperty("ajavaer.shiro.realm")
public class ShiroStart {
    @Resource
    private ShiroConfig shiroConfig;
    @Resource
    private CacheConfig cacheConfig;

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        if (shiroConfig.getFilterChainDefinition() != null) {
            Map<String, String> filter = new LinkedHashMap<>();
            List<String> anon = shiroConfig.getFilterChainDefinition().getAnon();
            if (anon != null) {
                anon.forEach(item -> filter.put(item, "anon"));
            }
            List<String> authc = shiroConfig.getFilterChainDefinition().getAuthc();
            if (authc != null) {
                authc.forEach(item -> filter.put(item, "authc"));
            }
            Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
            filters.put("ajax", new AjaxRequestFilter());
            filter.put("/**", "ajax");
            shiroFilterFactoryBean.setFilterChainDefinitionMap(filter);
        }
        if (shiroConfig.getLoginUrl() != null) {
            shiroFilterFactoryBean.setLoginUrl(shiroConfig.getLoginUrl());
        }
        if (shiroConfig.getSuccessUrl() != null) {
            shiroFilterFactoryBean.setSuccessUrl(shiroConfig.getSuccessUrl());
        }
        if (shiroConfig.getUnauthorizedUrl() != null) {
            shiroFilterFactoryBean.setUnauthorizedUrl(shiroConfig.getUnauthorizedUrl());
        }

        return shiroFilterFactoryBean;
    }


    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealms(shiroConfig.getAuthorizingRealm());
        securityManager.setCacheManager(redisCacheManager());
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    @Bean
    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        redisCacheManager.setExpire(2592000);
        redisCacheManager.setPrincipalIdFieldName("id");
        return redisCacheManager;
    }

    @Bean
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        List<CacheEngineConfig> engines = cacheConfig.getEngines();
        for (CacheEngineConfig engine : engines) {
            if (engine.getEngine() == CacheEngine.redis) {
                redisManager.setHost(engine.getHost() + ":" + engine.getPort());
                redisManager.setPassword(engine.getPassword());
            }
        }
        return redisManager;
    }

    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    @Bean
    public DefaultSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = null;
        if (shiroConfig.getWebSessionManager() != null) {
            sessionManager = shiroConfig.getWebSessionManager();
        } else {
            sessionManager = new DefaultWebSessionManager();
        }
        sessionManager.setSessionDAO(redisSessionDAO());
        sessionManager.setGlobalSessionTimeout(21600000);
        sessionManager.setDeleteInvalidSessions(true);
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        sessionManager.setCacheManager(redisCacheManager());
        return sessionManager;
    }

    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    /**
     * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     * 配置以下两个bean(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)即可实现此功能
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 开启aop注解支持
     *
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
